package datastructure.heap;

import java.util.Collection;
import java.util.Comparator;

/**
 * @Description: 二叉堆
 * @Author Ammar
 * @Create 2023/4/27 09:10
 */
public class BinaryHeap<E> extends AbstractHeap<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private E[] elements;

    public BinaryHeap() {
        super();
    }

    public BinaryHeap(E[] elements) {
        this(elements, null);
    }

    public BinaryHeap(Collection<E> elements) {
        this(elements, null);
    }

    public BinaryHeap(Comparator<E> comparator) {
        super(comparator);
        this.elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public BinaryHeap(Collection<E> elements, Comparator<E> comparator) {
        super(comparator);
        if (elements == null || elements.size() == 0) {
            this.elements = (E[]) new Object[DEFAULT_CAPACITY];
        } else {
            size = elements.size();
            int capacity = Math.max(size, DEFAULT_CAPACITY);
            this.elements = (E[]) new Object[capacity];
            int i = 0;
            for (E element : elements) {
                this.elements[i++] = element;
            }
            heapify();
        }
    }

    public BinaryHeap(E[] elements, Comparator<E> comparator) {
        super(comparator);
        if (elements == null || elements.length == 0) {
            this.elements = (E[]) new Object[DEFAULT_CAPACITY];
        } else {
            size = elements.length;
            int capacity = Math.max(elements.length, DEFAULT_CAPACITY);
            this.elements = (E[]) new Object[capacity];
            for (int i = 0; i < elements.length; i++) {
                this.elements[i] = elements[i];
            }
            heapify();
        }
    }

    @Override
    public void clear() {
        for (E element : elements) {
            element = null;
        }
        size = 0;
    }

    @Override
    public void add(E element) {
        elementNotNullCheck(element);
        ensureCapacity(size + 1);
        elements[size++] = element;
        siftUp(size - 1);
    }

    public void addAll(Collection<E> elements) {
        if (elements == null) return;
        for (E element : elements) {
            add(element);
        }
    }

    public void addAll(E[] elements) {
        if (elements == null) return;
        for (E element : elements) {
            add(element);
        }
    }

    @Override
    public E get() {
        emptyCheck();
        return elements[0];
    }

    @Override
    public E remove() {
        emptyCheck();
        E root = elements[0];
        // 最后一个元素放到堆顶
        elements[0] = elements[--size];
        // 删除最后一个元素
        elements[size] = null;
        // 下滤
        siftDown(0);
        return root;
    }

    @Override
    public E replace(E element) {
        elementNotNullCheck(element);
        if (size == 0) {
            elements[0] = element;
            size++;
            return null;
        }
        E root = elements[0];
        // 替换堆顶元素
        elements[0] = element;
        // 下滤
        siftDown(0);
        return root;
    }

    // 上滤
    private void siftUp(int index) {
        E element = elements[index];
        while (index > 0) {
            // 父节点的索引 根据完全二叉树的性质
            int parentIndex = (index - 1) >> 1;
            E parentElement = elements[parentIndex];
            if (compare(element, parentElement) <= 0) {
                break;
            }
            // 将父元素存储在index位置
            elements[index] = parentElement;
            // 重新赋值index
            index = parentIndex;
        }
        elements[index] = element;
    }

    // 下滤
    private void siftDown(int index) {
        E element = elements[index];
        // 第一个叶子节点的索引 == 非叶子节点的数量
        // index < 第一个叶子节点的索引
        // 必须保证index位置是非叶子节点
        int half = size >> 1;
        while (index < half) {
            // index的节点有两种情况
            // 1.只有左子节点
            // 2.同时有左右子节点
            // 默认为左子节点的索引
            int childIndex = (index << 1) + 1;
            // 默认index元素下滤到左子节点位置
            E childElement = elements[childIndex];
            // 右子节点的索引
            int rightIndex = childIndex + 1;
            // 右子节点有，且右子节点元素大于左子节点， 选出左右子节点最大的那个
            if (rightIndex < size && compare(elements[rightIndex], childElement) > 0) {
                // index 元素下滤到右子节点位置
                childElement = elements[childIndex = rightIndex];
            }
            // 如果index元素大于等于子节点，跳出循环
            if (compare(element, childElement) >= 0) {
                break;
            }
            // 将子节点存放到index位置
            elements[index] = childElement;
            // 重新赋值index
            index = childIndex;
        }
        elements[index] = element;
    }

    // 批量建堆
    private void heapify() {
        // 自上而下的上滤
//        for (int i = 1; i < size; i++) {
//            siftUp(i);
//        }
        // 自下而上的下滤
        for (int i = (size >> 1) - 1; i >= 0; i--) {
            siftDown(i);
        }
    }


    // 空检测
    private void emptyCheck() {
        if (size == 0) {
            throw new IndexOutOfBoundsException("Heap is empty");
        }
    }

    // 扩容
    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) {
            return;
        }
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[i];
        }
        elements = newElements;
    }

    // 元素判空
    private void elementNotNullCheck(E element) {
        if (element == null) {
            throw new IllegalArgumentException("Element must not be null");
        }
    }

    @Override
    public Object root() {
        return 0;
    }

    @Override
    public Object left(Object node) {
        Integer index = (Integer) node;
        index = (index << 1) + 1;
        return index >= size ? null : index;
    }

    @Override
    public Object right(Object node) {
        Integer index = (Integer) node;
        index = (index << 1) + 2;
        return index >= size ? null : index;
    }

    @Override
    public Object string(Object node) {
        return elements[(Integer) node];
    }
}
